//
//  BITabBarView.m
//  BIProjectModule
//
//  Created by yown on 2022/2/17.
//

#import "BITabBarView.h"

#import <BIToolModule/BIProjectDefine.h>
#import <BIProjectModule/BIAppDefine.h>
#import <BIToolModule/NSArray+Helper.h>

#import <Masonry/Masonry.h>

@interface BITabBarView ()

/// 分割线
@property (nonatomic) UIView *separatorView;
/// 背景图
@property (nonatomic) UIImageView *backgroundImageView;
/// tabbarItem数组
@property (nonatomic) NSMutableArray <BITabBarItemView *> *itemArray;
/// 点击回调
@property (nonatomic, copy) BITabBarClickBlock clickBlock;

@end

@implementation BITabBarView

#pragma mark - Init

- (instancetype)initWithFrame:(CGRect)frame clickBlock:(BITabBarClickBlock)clickBock {
    self = [super initWithFrame:frame];
    if (self) {
        self.clickBlock = clickBock;
        [self bi_setupData];
        [self bi_setupView];
        [self bi_setupLayout];
    }
    return self;
}

#pragma mark - Setup

- (void)bi_setupData {
    self.itemArray = [NSMutableArray array];
}

- (void)bi_setupView {
    self.backgroundColor = [UIColor whiteColor];
    
    self.separatorView = [UIView new];
    self.separatorView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.separatorView];
    
    self.backgroundImageView = [UIImageView new];
    self.backgroundImageView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.backgroundImageView];
}

- (void)bi_setupLayout {
    [self.separatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self);
        make.height.mas_equalTo(@(0.5));
    }];
    [self.backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
}

#pragma mark - Public Method

- (void)refreshTabBar:(NSArray <BITabItemModel *> *)modelArray isFocus:(BOOL)isFocus {
    // 如果强制，删除旧的视图和数据
    if (isFocus) {
        [self.itemArray enumerateObjectsUsingBlock:^(BITabBarItemView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        [self.itemArray removeAllObjects];
    }
    // 如果不存在子视图，则创建；存在，则直接刷新
    if (self.itemArray.count == 0) {
        // 创建新的tabbarItem
        __block CGFloat x = 0;
        CGFloat width = CGRectGetWidth(self.frame) / modelArray.count;
        CGFloat height = 49.0;
        [modelArray enumerateObjectsUsingBlock:^(BITabItemModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
            BITabBarItemView *itemView = [[BITabBarItemView alloc] initWithFrame:CGRectMake(x, 0, width, height) clickBlock:self.clickBlock];
            [itemView refreshTabBarItem:model];
            [self addSubview:itemView];
            [self.itemArray addObject:itemView];
            x = x + width;
        }];
    } else {
        [self.itemArray enumerateObjectsUsingBlock:^(BITabBarItemView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj refreshTabBarItem:[modelArray safeObjectAtIndex:idx]];
        }];
    }
}

@end
